package models

import "fmt"

func Calculate(category string) {
	var instorage []InStorage

	err := db.Table("in_storage").Where("category like ?", category).Order("intime ASC").Find(&instorage).Error //取入库表信息

	if err != nil {
		fmt.Println(err.Error())
	}

	var outstorage []OutStorage

	err = db.Table("out_storage").Where("category like ?", category).Order("out_time ASC").Find(&outstorage).Error //取出库表信息

	if err != nil {
		fmt.Println(err.Error())
	}

	i := 0
	flag := false
	var state float32
	for _, out := range outstorage {
		tons := out.Tons //暂存需要出库的吨数
		out.Fee = 0
		for tons != 0 {
			if instorage[i].Tons >= tons {
				state = float32((out.OutTime.Sub(instorage[i].InTime).Hours()) / 24)
				if state < 0 {
					flag = true //是否库存不足
					break
				}
				state = state - 13 //堆存的天数
				if state <= 0 {

				} else {
					out.Fee = out.Fee + (state * 0.5 * tons)
				}
				instorage[i].Tons -= tons
				tons = 0
			} else {
				if instorage[i].Tons == 0 {
					i++
				}
				state = float32((out.OutTime.Sub(instorage[i].InTime).Hours()) / 24) //计算时间差
				if state < 0 {
					flag = true //是否库存不足
					break
				}
				state = state - 13 //堆存的天数
				if state <= 0 {

				} else {
					out.Fee = out.Fee + (state * 0.5 * instorage[i].Tons)
				}
				tons -= instorage[i].Tons
				instorage[i].Tons = 0
				i++
			}

		}
		if !flag {
			db.Table("out_storage").Where("outid = ?", out.Outid).Update("fee", out.Fee)
		} else {
			db.Table("out_storage").Where("outid = ?", out.Outid).Update("text", "库存不足！！！")
			db.Table("out_storage").Where("outid = ?", out.Outid).Update("fee", 0)
			flag = false
		}
	}
}
